'''
Author: SUNNY
Description:    
Date: 2025-11-15 11:17:21
'''
"""
高级 MCP 服务器示例
包含资源管理、上下文使用等进阶功能
"""

from fastmcp import FastMCP, Context
import json
from datetime import datetime

mcp = FastMCP("智能工具库服务器 🚀")

# 资源定义
@mcp.resource("config://version")
def get_version() -> str:
    """获取服务器版本"""
    return "智能工具库 v2.0.0"

@mcp.resource("time://current")
def get_current_time() -> dict:
    """获取当前时间信息"""
    now = datetime.now()
    return {
        "timestamp": now.isoformat(),
        "year": now.year,
        "month": now.month,
        "day": now.day,
        "hour": now.hour,
        "minute": now.minute,
        "weekday": now.strftime("%A")
    }

# 工具定义
@mcp.tool()
async def text_analyzer(text: str, analysis_type: str, ctx: Context) -> dict:
    """文本分析工具

    对输入文本进行各种分析，包括统计和简单的情感分析。

    Args:
        text: 要分析的文本
        analysis_type: 分析类型 (length, words, sentiment)
        ctx:  上下文对象
    """
    await ctx.info(f"开始文本分析，类型: {analysis_type}")

    if analysis_type == "length":
        return {
            "char_count": len(text),
            "char_count_no_space": len(text.replace(" ", "")),
            "byte_size": len(text.encode('utf-8'))
        }
    elif analysis_type == "words":
        words = text.split()
        return {
            "word_count": len(words),
            "unique_words": len(set(words)),
            "avg_word_length": sum(len(word) for word in words) / len(words) if words else 0
        }   
    elif analysis_type == "sentiment":
        # 简单的情感分析（基于关键词）
        positive_words = ["好", "优秀", "棒", "高兴", "满意", "喜欢", "爱"]
        negative_words = ["差", "糟糕", "坏", "伤心", "不满", "讨厌", "恨"]

        positive_count = sum(1 for word in positive_words if word in text)
        negative_count = sum(1 for word in negative_words if word in text)

        if positive_count > negative_count:
            sentiment = "积极"
        elif negative_count > positive_count:
            sentiment = "消极"
        else:
            sentiment = "中性"

        return {
            "sentiment": sentiment,
            "positive_words": positive_count,
            "negative_words": negative_count,
            "score": positive_count - negative_count
        }
    else:
        result = {"error": f"不支持的分析类型: {analysis_type}"}

    await ctx.info(f"文本分析完成: {result}")
    return result

@mcp.tool()
def unit_converter(value: float, from_unit: str, to_unit: str) -> dict:
    """单位换算工具

    支持常见的单位换算。

    Args:
        value: 要换算的数值
        from_unit: 原单位
        to_unit: 目标单位
    """
    conversions = {
        "length": {
            "meters": 1,
            "kilometers": 1000,
            "centimeters": 0.01,
            "miles": 1609.34,
            "feet": 0.3048
        },
        "temperature": {
            "celsius": lambda x: x,
            "fahrenheit": lambda x: (x - 32) * 5/9,
            "kelvin": lambda x: x - 273.15
        }
    }

    try:
        # 温度换算特殊处理
        if from_unit in conversions["temperature"] and to_unit in conversions["temperature"]:
            # 先转到摄氏，再转到目标单位 
            celsius = conversions["temperature"][from_unit](value)

            if to_unit == "celsius":
                result = celsius
            elif to_unit == "fahrenheit":
                result = celsius * 9/5 + 32
            elif to_unit == "kelvin":
                result = celsius + 273.15
            
            return {
                "original": f"{value} {from_unit}",
                "converted": f"{round(result, 2)} {to_unit}",
                "value": result
            }
        # 长度换算
        elif from_unit in conversions["length"] and to_unit in conversions["length"]:
            meters = value * conversions["length"][from_unit]
            result = meters / conversions["length"][to_unit]

            return {
                "original": f"{value} {from_unit}",
                "converted": f"{round(result, 2)} {to_unit}",
                "value": result
            }
        else:
            return {"error": f"不支持的单位换算: {from_unit} 到 {to_unit}"}
    except Exception as e:
        return {"error": f"换算失败: {str(e)}"}
    
if __name__ == "__main__":
    mcp.run(transport="stdio")